<template>
	<div class="">
		<el-upload :action="uploadAction" :on-preview="handlePreview" :on-remove="handleRemove" :file-list="fileLists"
			:headers='headers' :on-error="handleUploadError" :on-success="handleUploadSuccess" list-type="picture-card">
			<i class="el-icon-plus"></i>
		</el-upload>
		<el-dialog :visible.sync="dialogVisible">
			<img width="70%" :src="dialogImageUrl" alt="">
		</el-dialog>
	</div>
</template>
<script>
	import axios from 'axios';
	export default {
		props: {
			fileLists: {
				type: Array
			},
			
			uploadAction: {
				type: String,
				required: true
			},
			removeAction: {
				type: String,
				required: true
			},
			headers: {
				type: Object
			},
			//默认图片
			defaultImage: {
				type: String
			},
		},
		data() {
			return {
				dialogImageUrl: '',
				dialogVisible: false,
			};
		},
		methods: {
			//删除图片
			async handleRemove(file, fileList) {
				// 如果不是默认头像，物理删除图片
				
				if (file.url != this.defaultImage) {
					let src='';
					if(file.hasOwnProperty('response')){
						src = file.response.src;
					}else{
						src=file.url
					}
					let { status } = await axios.delete(this.removeAction, { params: { src: src } });
					if (status) {
						this.$emit('fileListSuccess', this.convert(fileList));
						this.$message.success('删除成功!');
					}
				}
			},
			// 上传图片成功
			handleUploadSuccess(res, file,fileList) {
				// 触发外部绑定的事件
				this.$emit('fileListSuccess', this.convert(fileList));
			},
			// 上传图片失败
			handleUploadError({ status, message }, file, fileList) {
				switch (status) {
					case 401:
						this.$message.error(`错误:401,Token失效,请重新登录!`);
						break;
					case 400:
						message = JSON.parse(message);
						this.$message.error(`错误:400,${message}`);
						break;
					default:
						this.$message.error(`错误:${status},${message}!`);
						break;
				}
			},
			//字符串转换
			convert(data){
				let dataString=[];
				data.forEach((item,index)=>{
					dataString.push(item.url)
				});
				return dataString.join(',')
			},
			handlePreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			}
		},

	}
</script>
